
package com.samh.openrower2;

import android.util.Log;
import android.os.IBinder;
import android.os.SystemClock;
import android.content.Intent;
import android.app.Service;
import android.widget.Chronometer;

/**
* This Class represents the StopWatch.
* 
*/
public class StopWatchService extends Service {
	
	private static final String TAG = "StopWatch";
	
	public long firstStartTime = 0;
	
	public long startTime = 0;
	
	public long stopTime = 0;
	
	public long elapsedTime;
	
	public long elapsedHrs = 0;
	
	public long elapsedMins = 0;

	public long elapsedSecs = 0;
	
	public long elapsedMils = 0;
	
	public boolean running = false;
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public void start(Chronometer ch) {
		
		if(!running) {
			
			startTime = SystemClock.elapsedRealtime();
			
			firstStartTime = startTime;
			
			ch.setBase(startTime + stopTime);
			ch.start();
			
			running = true;
		}
	}
	
	public void stop(Chronometer ch) {
		
		if(running) {
			ch.stop();
			stopTime = ch.getBase() - SystemClock.elapsedRealtime();
			recordElapsedTime(ch);
			running = false;	
		} else {
			reset(ch);
		}
		
	}
	
	public void reset(Chronometer ch) {
		
		if(!running) {
			
			ch.setBase(SystemClock.elapsedRealtime());
			stopTime = 0;
			
		}
	}
	
	public void recordElapsedTime(Chronometer ch) {
		
		elapsedTime = (stopTime - startTime);
		elapsedSecs = elapsedTime / 1000;
		elapsedMils = elapsedTime - (elapsedSecs * 1000);
		elapsedMins = elapsedSecs / 60;
		elapsedHrs = elapsedMins / 60;
		//Log.d(TAG, "Elapsed Time:"+Long.toString(elapsedTime));
		
	}
	
	public long runningTime() {
		
		if(running) {
			return SystemClock.elapsedRealtime() - startTime;
		} else {
			return 0;
		}
	}
	
	
	
}
